import logging
from typing import Optional
from fastapi import APIRouter, Depends, Query, Path
from pydantic import BaseModel, Field
from sqlalchemy import text
from sqlalchemy.engine import create
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session

from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from routers.faultRouter.faultDanger import delete_fault
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

fault_level_router = APIRouter(prefix="/fault/faultLevel", tags=["故障等级管理"], dependencies=[Depends(oauth2_scheme)])


class FaultLevelSearch(PaginationBase):
    ffaultname: str = Field("", description="故障等级名称")


@fault_level_router.get("/list", summary="故障等级查询接口")
def list_fault_level(search: FaultLevelSearch = Query(), db: Session = Depends(get_db)):
    param = {}
    sql = "select  count(1) from s_ts_fault_level where 1=1"
    if search.ffaultname != "":
        sql = sql + " and ffaultname like concat('%', :ffaultname ,'%')"
        param["ffaultname"] = search.ffaultname
    count = db.execute(text(sql), param).scalar()

    param = {}
    sql = "select ffaultno,ffaultname,fupddate,foperator"
    sql = sql + " from s_ts_fault_level where 1=1"
    if search.ffaultname != "":
        sql = sql + " and ffaultname like concat('%', :ffaultname ,'%')"
        param["ffaultname"] = search.ffaultname
    if search.order == "desc":
        sql = sql + " order by  ffaultno desc "
    else:
        sql = sql + " order by  ffaultno "
    sql = sql + " limit :limit offset :offset "
    param["offset"] = search.offset
    param["limit"] = search.limit
    data = db.execute(text(sql), param).fetchall()

    data_list = []
    for key in range(len(data)):
        d1 = {}
        d1['ffaultno'] = data[key][0]
        d1['ffaultname'] = data[key][1]
        d1['fupddate'] = data[key][2]
        d1['foperator'] = data[key][3]
        data_list.append(d1)

    info_dict = {"list": data_list,
                 "limit": search.limit,
                 "page": search.pageIndex,
                 "pages": (count + search.pageIndex - 1) // search.pageSize,
                 "total": count}
    return BaseResponse.success(data=info_dict)


class FaultLevelCreate(BaseModel):
    """故障等级新增请求参数"""
    ffaultno: str = Field(..., description="故障等级编号（唯一标识）")
    ffaultname: str = Field(..., description="故障等级名称")
    foperator: str = Field(..., description="操作人")
    fupddate: str = Field(..., description="更新日期(yyyy-MM-dd HH:mm:ss)")


@fault_level_router.post("/create", summary="新增故障等级")
def create_fault_level(create: FaultLevelCreate, db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "select ffaultno from s_ts_fault_level where ffaultno= :ffaultno "
            data = db.execute(text(sql), {
                "ffaultno": create.ffaultno,
            }).fetchone()

            if len(data) > 0:
                return BaseResponse.error(message="编号已存在")
            else:
                sql = "insert into s_ts_fault_level(ffaultno,ffaultname,fupddate,foperator)"
                sql = sql + " values( :ffaultno , :ffaultname , :fupddate , :foperator );"
                db.execute(text(sql), {
                    "ffaultno": create.ffaultno,
                    "ffaultname": create.ffaultname,
                    "fupddate": create.fupddate,
                    "foperator": create.foperator,
                })
                # 返回
                d1 = {}
                d1["ffaultno"] = create.ffaultno
                d1["ffaultname"] = create.ffaultname
                d1["fupddate"] = create.fupddate
                d1["foperator"] = create.foperator
                return BaseResponse.success(data=d1)
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


@fault_level_router.post("/update", summary="故障等级修改接口")
def update_fault_level(update: FaultLevelCreate, db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "update s_ts_fault_level"
            sql = sql + " set ffaultname= :ffaultname "
            sql = sql + ",fupddate= :fupddate ,foperator= :foperator "
            sql = sql + " where ffaultno= :ffaultno "
            db.execute(text(sql), {
                "ffaultno": update.ffaultno,
                "ffaultname": update.ffaultname,
                "fupddate": update.fupddate,
                "foperator": update.foperator,
            })
            return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


@fault_level_router.post("/delete/{ffaultno}", summary="删除故障等级接口")
def delete_fault_level(ffaultno: str = Path(description="故障等级id"), db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "delete from s_ts_fault_level where ffaultno= :ffaultno "
            db.execute(text(sql), {
                "ffaultno": ffaultno,
            })
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")
